
package com.cicigodd.brick.plug.jwt.operate;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.cicigodd.brick.plug.common.exception.AuthException;
import com.cicigodd.brick.plug.jwt.api.JwtServiceApi;
import com.cicigodd.brick.plug.jwt.constants.JwtConstants;
import com.cicigodd.brick.plug.jwt.entity.DefaultJwtPayload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * jwt操作实现类
 *
 * @author cicigodd
 * @date 2022/09/23 08:42:00
 */
@Component
public class JwtServiceServiceImpl implements JwtServiceApi {


    @Override
    public String generateToken(Map<String, Object> payload) {

        // 计算过期时间
        DateTime expirationDate = DateUtil.offsetMillisecond(new Date(), Convert.toInt(JwtConstants.DEFAULT_JWT_MONTH));

        // 构造jwt token
        return Jwts.builder()
                .setClaims(payload)
                .setIssuedAt(new Date())
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, JwtConstants.JWTSECRET)
                .compact();
    }

    @Override
    public String generateTokenDefaultPayload(DefaultJwtPayload defaultJwtPayload) {

        // 计算过期时间
        DateTime expirationDate = DateUtil.offsetMonth(new Date(), JwtConstants.DEFAULT_JWT_MONTH);
        System.out.println(expirationDate.toString());
        System.out.println(expirationDate.getTime());
        // 设置过期时间
        defaultJwtPayload.setExpirationDate(expirationDate.getTime());

        // 构造jwt token
        return Jwts.builder()
                .setClaims(BeanUtil.beanToMap(defaultJwtPayload))
                .setSubject(defaultJwtPayload.getUserId().toString())
                .setIssuedAt(new Date())
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, JwtConstants.JWTSECRET)
                .compact();
    }

    @Override
    public Claims getJwtPayloadClaims(String token) {
        return Jwts.parser()
                .setSigningKey(JwtConstants.JWTSECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    @Override
    public DefaultJwtPayload getDefaultPayload(String token) {
        Map<String, Object> jwtPayload = getJwtPayloadClaims(token);
        return BeanUtil.toBeanIgnoreError(jwtPayload, DefaultJwtPayload.class);
    }

    @Override
    public boolean validateToken(String token) {
        try {
            getJwtPayloadClaims(token);
            return true;
        } catch (io.jsonwebtoken.JwtException jwtException) {
            return false;
        }
    }

    @Override
    public void validateTokenWithException(String token) {

        // 1.先判断是否是token过期了
        boolean tokenIsExpired = this.validateTokenIsExpired(token);
        if (tokenIsExpired) {
            throw new AuthException("令牌已过期");
        }

        // 2.判断是否是jwt本身的错误
        try {
            getJwtPayloadClaims(token);
        } catch (Exception e) {
            throw new AuthException("令牌解析错误");
        }
    }

    @Override
    public boolean validateTokenIsExpired(String token) {
        try {
            Claims claims = getJwtPayloadClaims(token);
            final Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

}
